/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.actions;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.ipo.mm.ejb.entities.City;
import org.ipo.mm.ejb.entities.Institution;
import org.ipo.mm.ejb.entities.InstitutionFamily;
import org.ipo.mm.ejb.entities.InstitutionRegion;
import org.ipo.mm.ejb.entities.InstitutionType;
import org.ipo.mm.ejb.entities.User;
import org.ipo.mm.ejb.facade.city.CityFacadeLocal;
import org.ipo.mm.ejb.facade.family.InstitutionFamilyFacadeLocal;
import org.ipo.mm.ejb.facade.institution.InstitutionFacadeLocal;
import org.ipo.mm.ejb.facade.log.LogFacadeLocal;
import org.ipo.mm.ejb.facade.region.InstitutionRegionFacadeLocal;
import org.ipo.mm.ejb.facade.type.InstitutionTypeFacadeLocal;
import org.ipo.mm.web.formbeans.InstitutionBean;
import org.ipo.mm.web.util.BreadCrumbs;
import org.ipo.mm.web.util.ConstantManager;
import org.ipo.mm.web.util.UTFEncoder;

/**
 *
 * @author makcro
 */
public class InstitutionAction extends org.apache.struts.action.Action {

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward actionForward = null;

        MessageResources mResources = getResources(request);
        String saveOperaton = mResources.getMessage(getLocale(request), "gen_create");
        String updateOperation = mResources.getMessage(getLocale(request), "gen_update");
        String createType = mResources.getMessage(getLocale(request), "types_create");
        String createFamily = mResources.getMessage(getLocale(request), "families_create");
        String createRegion = mResources.getMessage(getLocale(request), "regions_create");
        String createCity = mResources.getMessage(getLocale(request), "cities_create");

        if (isCancelled(request)) {
            actionForward = executeCancel(mapping, form, request, response);
        } else {

            User currentUser = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);

            InstitutionBean instBean = (InstitutionBean) form;

            String operation = instBean.getOperation();
             operation = UTFEncoder.encode(operation);
            //operation = UTFEncoder.clearSerbianLetters(operation);
            if (saveOperaton.equals(operation)) {
                actionForward = executeCreate(mapping, request, response, instBean, currentUser);
            } else if (updateOperation.equals(operation)) {
                actionForward = executeUpdate(mapping, request, response, instBean, currentUser);
            } else if (createType.equals(operation)) {
                actionForward = new ActionForward("/protected/dispatch.do?method=showCreateTypeForm", true);
                request.getSession().setAttribute(ConstantManager.SESSION_INST_RESET_FORM, new Boolean(false));
            } else if (createFamily.equals(operation)) {
                actionForward = new ActionForward("/protected/dispatch.do?method=showCreateFamilyForm", true);
                request.getSession().setAttribute(ConstantManager.SESSION_INST_RESET_FORM, false);
            } else if (createRegion.equals(operation)) {
                actionForward = new ActionForward("/protected/dispatch.do?method=showCreateRegionForm", true);
                request.getSession().setAttribute(ConstantManager.SESSION_INST_RESET_FORM, new Boolean(false));

            } else if (createCity.equals(operation)) {
                actionForward = new ActionForward("/protected/dispatch.do?method=showCreateCityForm", true);
                request.getSession().setAttribute(ConstantManager.SESSION_INST_RESET_FORM, new Boolean(false));

            }


        }
        return actionForward;
    }

    private ActionForward executeCreate(ActionMapping mapping,
            HttpServletRequest request,
            HttpServletResponse response,
            InstitutionBean institutionBean,
            User user) throws Exception {


        ActionForward actionForward = null;


        Institution institution = new Institution();

        int iFamilyId = Integer.valueOf(institutionBean.getFamily());
        int iRegionId = Integer.valueOf(institutionBean.getRegion());
        int iCityId = Integer.valueOf(institutionBean.getCity());
        int iTypeId = Integer.valueOf(institutionBean.getType());

        InstitutionFamily family = lookupInstitutionFamilyFacade().find(iFamilyId);
        InstitutionRegion region = lookupInstitutionRegionFacade().find(iRegionId);
        InstitutionType type = lookupInstitutionTypeFacade().find(iTypeId);
        City city = lookupCityFacade().find(iCityId);

        institution.setFamily(family);
        institution.setRegion(region);
        institution.setType(type);
        institution.setCity(city);
        institution.setUser(user);


        institution.setAddress(UTFEncoder.encode(institutionBean.getAddress()));
        institution.setEmail(UTFEncoder.encode(institutionBean.getEmail()));
        institution.setFax(UTFEncoder.encode(institutionBean.getFax()));
        institution.setName(UTFEncoder.encode(institutionBean.getName()));
        institution.setNote(UTFEncoder.encode(institutionBean.getNote()));
        institution.setTelephone(UTFEncoder.encode(institutionBean.getTelephone()));
        institution.setZip(UTFEncoder.encode(institutionBean.getZip()));
        institution.setWeb(UTFEncoder.encode(institutionBean.getWeb()));
        lookupInstitutionFacade().create(institution);


        // store obj in request so it can be automatically selected in list
        request.setAttribute(ConstantManager.REQUEST_INSTITUTION_LAST_CREATED, institution);

        //log
        lookupLogFacade().logCreate(user, ConstantManager.INSTITUTION_NAME, institution.getName());

        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_CREATE, request);
        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        bc.pop();
        actionForward = bc.pop().getActionForward();

        request.getSession().setAttribute(ConstantManager.SESSION_INST_RESET_FORM, new Boolean(true));


        return actionForward;
    }

    private ActionForward executeUpdate(ActionMapping mapping,
            HttpServletRequest request,
            HttpServletResponse response,
            InstitutionBean institutionBean,
            User user) throws Exception {

        ActionForward actionForward = null;


        Institution institution = (Institution) request.getSession().getAttribute("dispatcher_showUpdateInstForm_inst");

        institution.setAddress(institutionBean.getAddress());

        City city = lookupCityFacade().find(Integer.valueOf(institutionBean.getCity()));
        institution.setCity(city);

        InstitutionRegion institutionRegion = lookupInstitutionRegionFacade().find(Integer.valueOf(institutionBean.getRegion()));
        institution.setRegion(institutionRegion);

        InstitutionFamily family = lookupInstitutionFamilyFacade().find(Integer.valueOf(institutionBean.getFamily()));
        institution.setFamily(family);

        InstitutionType type = lookupInstitutionTypeFacade().find(Integer.valueOf(institutionBean.getType()));
        institution.setType(type);


        institution.setAddress(UTFEncoder.encode(institutionBean.getAddress()));
        institution.setEmail(UTFEncoder.encode(institutionBean.getEmail()));
        institution.setFax(UTFEncoder.encode(institutionBean.getFax()));
        institution.setName(UTFEncoder.encode(institutionBean.getName()));
        institution.setNote(UTFEncoder.encode(institutionBean.getNote()));
        institution.setTelephone(UTFEncoder.encode(institutionBean.getTelephone()));
        institution.setZip(UTFEncoder.encode(institutionBean.getZip()));
        institution.setWeb(UTFEncoder.encode(institutionBean.getWeb()));

        lookupInstitutionFacade().edit(institution);

        //log
        lookupLogFacade().logUpdate(user, ConstantManager.INSTITUTION_NAME, institution.getName());

        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_UPDATE, request);

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        bc.pop();
        actionForward = bc.pop().getActionForward();

        request.getSession().setAttribute(ConstantManager.SESSION_INST_RESET_FORM, new Boolean(true));
        request.getSession().setAttribute("dispatcher_showUpdateInstForm_inst", institution);



        return actionForward;
    }

    private ActionForward executeCancel(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        request.getSession().setAttribute(ConstantManager.SESSION_INST_RESET_FORM, new Boolean(true));

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        bc.pop();
        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }

    private InstitutionTypeFacadeLocal lookupInstitutionTypeFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionTypeFacadeLocal) c.lookup("java:comp/env/InstitutionTypeFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionRegionFacadeLocal lookupInstitutionRegionFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionRegionFacadeLocal) c.lookup("java:comp/env/InstitutionRegionFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionFamilyFacadeLocal lookupInstitutionFamilyFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionFamilyFacadeLocal) c.lookup("java:comp/env/InstitutionFamilyFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private CityFacadeLocal lookupCityFacade() {
        try {
            Context c = new InitialContext();
            return (CityFacadeLocal) c.lookup("java:comp/env/CityFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionFacadeLocal lookupInstitutionFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionFacadeLocal) c.lookup("java:comp/env/InstitutionFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private LogFacadeLocal lookupLogFacade() {
        try {
            Context c = new InitialContext();
            return (LogFacadeLocal) c.lookup("java:comp/env/LogFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

     private void notifyOperatoinStatus(String operationMessageKey, HttpServletRequest request) {

        MessageResources mResources = getResources(request);
        String typeEntityName = mResources.getMessage(getLocale(request), ConstantManager.INSTITUTION_ENTITY_NAME_RES_KEY);

        ActionMessages messages = new ActionMessages();
        ActionMessage actionMessage = new ActionMessage(operationMessageKey, typeEntityName);
        messages.add("operation_status", actionMessage);
        saveMessages(request, messages);

    }
    
}
